package com.guet.careapp.service.impl;

import com.aliyuncs.exceptions.ClientException;
import com.guet.careapp.cache.CacheListener;
import com.guet.careapp.cache.CacheManagerImpl;
import com.guet.careapp.cache.CacheManagerUtils;
import com.guet.careapp.cache.ICacheManager;
import com.guet.careapp.common.Constants;
import com.guet.careapp.controller.rest.common.errorCode.Error;
import com.guet.careapp.pojo.TUserGuardianInfo;
import com.guet.careapp.pojo.TUserInfo;
import com.guet.careapp.pojo.TUserUnderGuardiansInfo;
import com.guet.careapp.service.ISMSService;
import com.guet.careapp.service.IUserGuardianInfoService;
import com.guet.careapp.service.IUserInfoService;
import com.guet.careapp.service.IUserUnderGuardiansInfoService;
import com.guet.careapp.service.base.ServiceSupportImpl;
import com.guet.careapp.utils.MD5Util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.guet.careapp.utils.TimeHelper;
import com.guet.careapp.utils.VerifyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by LXM on 2017/10/27.
 *
 * @author LXM
 * @version 1.0
 * @description
 * @datetime 11:45
 */
@Service("userInfoService")
public class UserInfoServiceImpl extends ServiceSupportImpl<TUserInfo> implements IUserInfoService {

    protected Logger logger = LoggerFactory.getLogger(UserInfoServiceImpl.class);

    @Autowired
    private IUserGuardianInfoService guardianInfoService;

    @Autowired
    private IUserUnderGuardiansInfoService underGuardiansInfoService;

    @Autowired
    private ISMSService ismsService;

    @Override
    public Error checkVerify(String tel, String verify) {
        Object obj = CacheManagerUtils.getInstance().getCacheByKey(tel).getDatas();
        if (obj == null) return Error.Invaild;
        String org = (String) obj;
        if (org.trim().equals(""))
            return Error.TimeOut;
        else if (!org.trim().equals(verify))
            return Error.Invaild;
        return Error.Success;
    }

    @Override
    public Error registe(String username, String psw, String tel, String type, String device) {
        TUserInfo user;
        List<TUserInfo> l;
        try {
            l = queryByHql(
                    "SELECT t FROM TUserInfo t WHERE t.name = \'" + username + "\' OR t.telphone=\'" + tel + "\'");
            int i;
        } catch (Exception e) {
            return Error.Unkonwn;
        }
        if (l.size() != 0) {
            return Error.AreadyExist;
        }

        user = new TUserInfo();
        user.setName(username);
        user.setPassward(MD5Util.MD5(psw));
        user.setTelphone(tel);
        user.setType(type);
        user.setRegisTime(TimeHelper.getTime());
        user.setImage("");
        user.setDeviceId(device);
        try {
            save(user);
        } catch (Exception e) {
            return Error.Unkonwn;
        }


        l = queryByHql("SELECT t FROM TUserInfo t WHERE t.name = \'" + username + "\' AND t.telphone=\'" + tel + "\'");
        user = l.get(0);

//    List<TUserGuardianInfo> ll=  guardianInfoService.queryByHql("SELECT t FROM TUserGuardianInfo t ");
//    TUserGuardianInfo tUserGuardianInfo=ll.get(ll.size()-1);
//    List<TUserUnderGuardiansInfo> lll=  underGuardiansInfoService.queryByHql("SELECT t FROM TUserUnderGuardiansInfo t ");
//    TUserUnderGuardiansInfo tUserUnderGuardiansInfo=lll.get(lll.size()-1);
        //根据类型，写入数据库
        if (type.equals("1")) {
            try {

                TUserGuardianInfo guardianInfo = new TUserGuardianInfo();
//          guardianInfo.setGId(tUserGuardianInfo.getGId()+1);
                guardianInfo.setUId(user.getUId());
                guardianInfo.setTUserInfo(user);
                guardianInfo.setPhone(tel);
                guardianInfo.setIdentifyNum("");
                guardianInfoService.save(guardianInfo);
            } catch (Exception e) {
                return Error.Unkonwn;
            }
        } else if (type.equals("2")) {
            try {
                TUserUnderGuardiansInfo userUnderGuardiansInfo = new TUserUnderGuardiansInfo();
//                userUnderGuardiansInfo.setUgId(tUserUnderGuardiansInfo.getUgId() + 1);
                userUnderGuardiansInfo.setUgId(user.getUId());
                userUnderGuardiansInfo.setTUserInfo(user);
                userUnderGuardiansInfo.setAge(0);
                userUnderGuardiansInfo.setBodycondition("");
                underGuardiansInfoService.save(userUnderGuardiansInfo);

            } catch (Exception e) {
                return Error.Unkonwn;
            }
        }
        //调用服务层注册的方法，成功后则返回一个返回码。需要检查是否用户名已经存在。
        return Error.Success;
    }

    /**
     * 发送短信验证码的服务
     *
     * @param phone
     * @return
     */
    @Override
    public Error askForVerifyCode(String phone) {

        if (!VerifyUtils.isMobiPhoneNum(phone)) {
            logger.error(phone + "申请验证码失败");
            logger.error(phone + "手机无效");
            return Error.Invaild;
        }
        //获取验证码
        String code = VerifyUtils.ramdomInt();
        //验证码保存在缓存中
        CacheManagerImpl cacheManager = CacheManagerUtils.getInstance();
        cacheManager.putCache(phone, code, Constants.CACHE_TIMETOLIVE);
        CacheListener cacheListener = new CacheListener(cacheManager);
        cacheListener.startListen();
        //发送给用户手机
        try {
            logger.info("用户" + phone + "申请的验证码为：" + code);
            ismsService.sendSms(phone, "{\"code\":\"" + code + "\"}", Constants.VERIFY_TEMPLATE);
        } catch (ClientException e) {
            logger.error(e.toString());
            return Error.Unkonwn;
        }
        return Error.Success;
    }

    /**
     * 修改个人信息的服务
     *
     * @param map
     * @return
     */
    @Override
    public Error changeInfo(Map map) {

        String uid = "" + map.get("u_id");
        String tel = "" + map.get("telephone");
        String username = "" + map.get("username");
        String psw = "" + map.get("password");
        String device = "" + map.get("device_id");
        String img_url = "" + map.get("image");
        String remark = "" + map.get("remark");

        Map fieldMap = new HashMap();
        fieldMap.put("u_id", uid);
        TUserInfo user = findByField(fieldMap);
        if (user == null)
            return Error.NotFond;
        if (!tel.equals("null"))
            user.setTelphone(tel);
        if (!username.equals("null"))
            user.setName(username);
        if (!psw.equals("null"))
            user.setPassward(psw);
        if (!device.equals("null"))
            user.setDeviceId(device);
        if (!img_url.equals("null"))
            user.setImage(img_url);
        if (!remark.equals(""))
            user.setRemark(remark);
        try {
            update(user);
        } catch (Exception e) {
            logger.error("修改个人信息出错");
            logger.error(e.toString());
            return Error.Unkonwn;
        }
        return Error.Success;
    }

    @Override
    public Error login(Map map) {
        String username = map.get("username") + "";
        String password = map.get("password") + "";
        String deviceId = map.get("device_id") + "";
        Map fieldMap = new HashMap();
        fieldMap.put("name", username);
        TUserInfo user = findByField(fieldMap);
        if (user == null)
            return Error.NotFond;
        if (password.equals(user.getPassward())) {
            user.setDeviceId(deviceId);
            try {
                update(user);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("登陆更新用户信息失败");
                return Error.Fail;
            }

            return Error.Success;
        }
        return Error.Fail;
    }


}
